/*
 * manager.h
 *
 *  Created on: Mar 21, 2012
 *      Author: yxjiang
 */

#ifndef MANAGER_H_
#define MANAGER_H_

#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <cstdlib>
#include <map>
#include <sstream>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "../common/common.h"
#include "crawler.h"

namespace event {

typedef struct
{
	Crawler *crawler;
	bool running;
	pthread_t pid;
} CrawlerStatus;

class Manager
{
public:
	/*
	 * Create a manager to manage all the crawlers, then register a stream to the collector.
	 */
	Manager(int port, float rate, std::string collector_ip, int collector_register_port);
	/*
	 * Stop the web service thread and all crawler threads.
	 */
	~Manager();
	/*
	 * Set the rate.
	 * Set the monitor interval in second.
	 * E.g. 2 means monitor every 2 seconds.
	 * 		0.5 means monitor every 0.5 seconds.
	 */
	void SetRate(float rate);
	/*
	 * Attach a new crawler.
	 */
	void Attach(Crawler *crawler);
	/*
	 * Detach an existing crawler.
	 */
	void Detach(const std::string &name);
	/*
	 * Get a particular crawler by its name.
	 */
	Crawler *GetCrawler(const std::string &name) const;
	/*
	 * Start all the crawlers, and start the web service.
	 * Each crawler is running in a separate thread.
	 */
	void StartService();

private:
	/*
	 * Start the crawler as a thread.
	 */
	static void *_CrawlerService(void *arg);
	/*
	 * Start a web service.
	 */
	static void *_WebService(void *arg);

	/*
	 * Generate the json and return it as text.
	 */
	static const std::string _AssembleJson();

	/*
	 * Self register to the collector.
	 */
	void _SelfRegistration(std::string collector_register_ip, int collector_register_port);

private:
	static bool service_stop_;
	static int state_port_;		//	the port of manager to send the monitoring states
	static float rate_;
	static std::map<std::string, CrawlerStatus> crawlers_;
	pthread_t web_service_pid_;
	std::string collector_register_ip_;
	int collector_register_port_;
};

};



#endif /* MANAGER_H_ */
